package com.fhz.module_mine;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.fhz.core_lib.base.BaseApplication;
import com.fhz.core_lib.bus.LiveDataBus;
import com.fhz.core_lib.entity.LoggedInUser;
import com.fhz.core_lib.manager.DialogManager;
import com.fhz.core_lib.router.RouterActivityPath;
import com.fhz.core_lib.utils.ApiResponse;
import com.fhz.core_lib.utils.SPUtils;
import com.fhz.core_lib.widget.DialogView;
import com.fhz.module_mine.databinding.ActivityMineBinding;
import com.fhz.module_mine.databinding.MineFragmentBinding;
import com.fhz.module_mine.fileutils.FileHelper;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

public class MIneActivity extends AppCompatActivity implements View.OnClickListener{

    private MineViewModel mViewModel;
    private File uploadFile = null;
    public DialogView selectProfileDialog;
    private ActivityMineBinding activityMineBinding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        activityMineBinding = DataBindingUtil.setContentView(this, R.layout.activity_mine);


        selectProfileDialog = DialogManager.getInstance().createDialog(this,R.layout.select_dialog_layout, Gravity.BOTTOM);
        selectProfileDialog.findViewById(R.id.take_picture).setOnClickListener(this);
        selectProfileDialog.findViewById(R.id.open_album).setOnClickListener(this);
        selectProfileDialog.findViewById(R.id.cancel).setOnClickListener(this);

        mViewModel = new ViewModelProvider(this, new MineViewModelFactory()).get(MineViewModel.class);


    }

    public static void Launch(Activity activity){
        Intent intent = new Intent(activity, MIneActivity.class);
        activity.startActivity(intent);
    }

    public void changeProfileImage(View view) {
        DialogManager.getInstance().show(selectProfileDialog);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.take_picture) {
            DialogManager.getInstance().hide(selectProfileDialog);
            //打开相机--> 需要权限
            //storage/emulated/0/feng.jpg
            //File file = new File("/storage/emulated/0/feng.jpg");
            //跳转到相机
            FileHelper.getInstance().toCamera(this);
        } else if (id == R.id.open_album) {//访问本地的相册 --> 需要权限
            DialogManager.getInstance().hide(selectProfileDialog);
            //跳转到相册
            FileHelper.getInstance().toAlbum(this);
        } else if (id == R.id.cancel) {
            DialogManager.getInstance().hide(selectProfileDialog);
        }
    }

    //不管是相机还是本地的图片,都是要最后上传的.
    /**
     * 上传逻辑是这样的
     * 先从后台取到七牛的token
     * 然后在前端上传图片到七牛
     * 上传成功后,把图片的完整路径发给后端
     * 后端存到数据库
     * 这样用户的信息每次读取都是真是的图片地址
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("requestCode:" , requestCode+"");
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == FileHelper.CAMEAR_REQUEST_CODE) {
                FileHelper.getInstance().startPhotoZoom(this, FileHelper.getInstance().getTempFile());
            } else if (requestCode == FileHelper.ALBUM_REQUEST_CODE) {
                Uri uri = data.getData();
                if (uri != null) {
                    String path = FileHelper.getInstance().getRealPathFromURI(getApplicationContext(), uri);
                    if (!TextUtils.isEmpty(path)) {
                        uploadFile = new File(path);
                        FileHelper.getInstance().startPhotoZoom(this, uploadFile);
                    }
                }
            } else if (requestCode == FileHelper.CAMERA_CROP_RESULT) {
                Log.i("a","CAMERA_CROP_RESULT");
                uploadFile = new File(FileHelper.getInstance().getCropPath());
                Log.i("uploadPhotoFile:" , uploadFile.getPath());

                //将裁切后的头像上传
                UploadManager uploadManager = new UploadManager();
                mViewModel.getQiNiuToken().observe(this, new Observer<ApiResponse<String>>() {
                    @Override
                    public void onChanged(ApiResponse<String> stringApiResponse) {
                        String absolutePath = uploadFile.getAbsolutePath();
                        String fileName = absolutePath.substring(absolutePath.lastIndexOf("/")+1,absolutePath.lastIndexOf("."));
                        String token = stringApiResponse.getData();
                        Log.i("token", "onChanged: "+token);
                        uploadManager.put(uploadFile, fileName, token, new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject response) {
                                Log.i("key",fileName);
                                //取到上传的链接后,调用后端更新接口,更新用户的头像.
                                //http://qiniu.fenghongzhang.com/IMG_20211116_200142
                                String headImg = "http://qiniu.fenghongzhang.com/".concat(fileName);
                                mViewModel.updateUser(SPUtils.getInstance().getString(SPUtils.NICKNAME,""),headImg)
                                        .observe(MIneActivity.this, new Observer<ApiResponse<LoggedInUser>>() {
                                            @Override
                                            public void onChanged(ApiResponse<LoggedInUser> loggedInUserApiResponse) {
                                                if(loggedInUserApiResponse.getData() != null){
                                                    Toast.makeText(MIneActivity.this, "头像更新成功!", Toast.LENGTH_SHORT).show();
//                                                    LiveDataBus.get().with("headImg").postValue(loggedInUserApiResponse.getData().getHeadImage());
                                                    EventBus.getDefault().post(loggedInUserApiResponse.getData().getHeadImage());
                                                }
                                            }
                                        });

                            }
                        },null);
                    }
                });
            }
            //设置头像
            if (uploadFile != null) {
                Bitmap mBitmap = BitmapFactory.decodeFile(uploadFile.getPath());
                activityMineBinding.profileImage.setImageBitmap(mBitmap);
            }
        }
    }
}